import http from "../apis/http";
import { SMART_HOMEWORK } from "../apis/host";
import OSS from "ali-oss";
const API = {
  getOssToken: "/v1/common/upload/ststoken",
};

// 1、阿里云上传文件
// https://help.aliyun.com/zh/oss/user-guide/simple-upload?spm=a2c4g.11186623.help-menu-31815.d_4_3_1_0.266e762dT4nuss&scm=20140722.H_31848._.OR_help-T_cn~zh-V_1#b1cef61e9aarn
interface IOssToken {
  AccessKeyId: string;
  AccessKeySecret: string;
  SecurityToken: string;
  Expiration: number; // 过期时间
  bucket: string;
  region: string;
}
let localToken: IOssToken = {
  AccessKeyId: "",
  AccessKeySecret: "",
  SecurityToken: "",
  Expiration: 0,
  bucket: "",
  region: "",
};
// 公司唯一获取阿里云的token：作业系统提供
const getOssToken = (policy = 0): Promise<IOssToken> => {
  return http.get(SMART_HOMEWORK + API.getOssToken, {
    params: {
      policy,
    },
  });
};

const getValidToken = async () => {
  // 过期重新获取
  if (!localToken.Expiration || Date.now() / 1000 > localToken.Expiration) {
    localToken = await getOssToken();
  }
  return localToken;
};

const aliUploadFile = async (file: File) => {
  const tokenData = await getValidToken();
  let ossConfig = {
    region: tokenData.region,
    accessKeyId: tokenData.AccessKeyId,
    accessKeySecret: tokenData.AccessKeySecret,
    stsToken: tokenData.SecurityToken,
    bucket: tokenData.bucket,
    secure: true,
  };
  let client = new OSS(ossConfig);
  let Filepath = "/ailearn/teacher/" + file.name;
  let result = await client.put(Filepath, file, {
    headers: {
      "x-oss-object-acl": "public-read",
    },
  });

  return {
    name: result.name.slice(16),
    url: result.url,
    type: file.type,
  };
};



// 2、七牛云上传文件

export { aliUploadFile };
